const Router = require('koa-router')
const router = new Router({ prefix: '/user' })

const UserController = require('../../controller/user')

const validator = require('../../middleware/validator')
const Joi = require('joi')
const Status = require('../../constant/status')

router.get(
  '/',
  validator({
    current: Joi.number(),
    size: Joi.number(),
    username: Joi.string().allow(''),
    nickName: Joi.string().allow(''),
    phoneNumber: Joi.string()
      .pattern(/^[1][3,4,5,7,8][0-9]{9}$/)
      .allow(''),
    email: Joi.string().email().allow(''),
    status: Joi.string().valid(...Object.values(Status))
  }),
  UserController.findAllUser
)

router.get('/:id', UserController.findUserById)

router.post(
  '/',
  validator({
    username: Joi.string().required(),
    password: Joi.string().required(),
    domain: Joi.string().allow('').default('built-in'),
    built_in: Joi.boolean().default(false),
    avatar: Joi.string(),
    nick_name: Joi.string().required(),
    phone_number: Joi.string()
    .pattern(/^[1][3,4,5,7,8][0-9]{9}$/)
    .required()
    .error(new Error('手机号码格式不正确')),
    email: Joi.string().email().error(new Error('邮箱格式不正确')),
    status: Joi.string()
      .valid(...Object.values(Status))
      .default('ENABLED')
  }),
  UserController.createUser
)

router.put(
  '/:id',
  validator({
    id: Joi.string().required(),
    username: Joi.string().allow(''),
    password: Joi.string().allow(''),
    domain: Joi.string().allow(''),
    built_in: Joi.boolean(),
    avatar: Joi.string().allow(null),
    nick_name: Joi.string(),
    phone_number: Joi.string()
    .pattern(/^[1][3,4,5,7,8][0-9]{9}$/)
    .error(new Error('手机号码格式不正确')),
    email: Joi.string().email(),
    status: Joi.string().valid(...Object.values(Status))
  }),
  UserController.updateUser
)

router.delete('/:id', UserController.deleteUser)

module.exports = router
